package com.ciaojian.store.controller.franchisees;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.core.enums.business.ScheduleTypeEnum;
import com.ciaojian.core.enums.business.WorkerApplyStatusEnum;
import com.ciaojian.core.mapper.RosterMapper;
import com.ciaojian.core.mapper.SchedulingMapper;
import com.ciaojian.core.mapper.WorkerAuthorityMapper;
import com.ciaojian.core.model.Roster;
import com.ciaojian.core.model.Scheduling;
import com.ciaojian.core.model.SchedulingExamine;
import com.ciaojian.core.model.vo.AuthorityGroupVo;
import com.ciaojian.core.util.Result;
import com.ciaojian.core.model.vo.CheckTodayUserVo;
import com.ciaojian.store.model.vo.SchedulDelVo;
import com.ciaojian.store.service.CheckUserServiceImpl;
import com.ciaojian.store.service.SchedulingServiceImpl;
import com.ciaojian.store.service.WorkerServiceImpl;
import io.swagger.annotations.*;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Api(tags = "加盟商排班接口")
@RestController
@RequestMapping("/franchisees/scheduling")
public class FSchedulingController {

    @Resource
    private SchedulingServiceImpl schedulingService;
    @Resource
    private SchedulingMapper schedulingMapper;
    @Resource
    private RosterMapper rosterMapper;
    @Resource
    private WorkerServiceImpl workerService;
    @Resource
    private WorkerAuthorityMapper workerAuthorityMapper;
    @Resource
    private CheckUserServiceImpl checkUserServiceImpl;



    @ApiOperation("员工排班")
    @PostMapping("/worker")
    public Result workerScheduling(@RequestBody List<Scheduling> schedulingList) {
        int count=0;
        Assert.isTrue(schedulingList.size()!=0, "请填入排班信息");
        for (Scheduling scheduling : schedulingList) {
            Scheduling schedulingOld = new Scheduling();
            try {
                schedulingOld = getSchedulingDroster(scheduling.getWorkerId(), scheduling.getDate());
            }catch (Exception e){

            }

            if (ObjectUtil.isNotNull(schedulingOld)){
                continue;
            }

            //请假
            if (scheduling.getRosterId()==1){
                scheduling.setType(ScheduleTypeEnum.LEAVE);
                scheduling.setStatus(WorkerApplyStatusEnum.PASS);
                //插入请假排班
                schedulingMapper.insert(scheduling);

            }else {
                //排班
                if (count == 0) {
                    count++;
                }
                if (scheduling.getRosterId()!=-1 && scheduling.getRosterId()!=1) {
                    Roster roster = rosterMapper.selectById(scheduling.getRosterId());
                    scheduling.setLunchStartTime(roster.getLunchStartTime());
                    scheduling.setLunchStartTime(roster.getLunchEndTime());
                    scheduling.setDinnerStartTime(roster.getDinnerStartTime());
                    scheduling.setStatus(WorkerApplyStatusEnum.PASS);
                    scheduling.setDinnerEndTime(roster.getDinnerEndTime());
                }
                schedulingMapper.insert(scheduling);
            }
        }
        return Result.ok();
    }

    private Scheduling getSchedulingDroster(Integer workerId, Date date) {
        QueryWrapper<Scheduling> schedulingQueryWrapper = new QueryWrapper<>();
        schedulingQueryWrapper.eq("worker_id",workerId);
        schedulingQueryWrapper.eq("date",date);
        schedulingQueryWrapper.in("status",0,1);
        Scheduling scheduling = schedulingMapper.selectOne(schedulingQueryWrapper);
        return scheduling;
    }


    @ApiOperation("审核通知数")
    @GetMapping("/apply-notice")
    public Result applyNotice(Integer storeId) {
        LambdaQueryWrapper<SchedulingExamine> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SchedulingExamine::getStoreId, storeId)
                .eq(SchedulingExamine::getRead, Boolean.FALSE)
                .eq(SchedulingExamine::getLogicDel, Boolean.FALSE);
        return Result.ok(new SchedulingExamine().selectCount(lambdaQueryWrapper));
    }

    /**
     * @Description: 查询班次
     * @Author: xiangchao
     * @Date: 2020/11/30 10:00 上午
     */
    @ApiOperation("查询班次")
    @GetMapping("/findDRosterList")
    public Result findDRosterList(@ApiParam(value = "门店ID", required = true) String storeId) {

        return workerService.findDRosterList(storeId);
    }

    @ApiOperation("本月已排班的日期")
    @GetMapping("/scheduled-month")
    public Result getScheduledMonth(
            @NotNull(message = "请选择门店") Integer storeId,
            @NotNull(message = "请选择开始日期") @DateTimeFormat(pattern = "yyyy-MM-dd") Date begin,
            @NotNull(message = "请选择结束日期") @DateTimeFormat(pattern = "yyyy-MM-dd") Date end
    ) {
        LambdaQueryWrapper<Scheduling> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Scheduling::getDate)
                .between(Scheduling::getDate, begin, end)
                .eq(Scheduling::getStoreId, storeId)
                .eq(Scheduling::getStatus, WorkerApplyStatusEnum.PASS)
                .eq(Scheduling::getLogicDel, Boolean.FALSE)
                .groupBy(Scheduling::getDate);
        return Result.ok(schedulingService.listObjs(lambdaQueryWrapper));
    }

    @ApiOperation("查询已排班的发型师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "日期", paramType = "query"),
            @ApiImplicitParam(name = "rosterId", value = "排班Id"),
            @ApiImplicitParam(name = "storeId", value = "门店Id")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功返回数据", response = Scheduling.class)})
    @GetMapping
    public Result getScheduled(@DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull(message = "日期不能为空") Date date,
                               Integer rosterId,
                               Integer storeId
    ) {
        LambdaQueryWrapper<Scheduling> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Scheduling::getDate, date)
                .eq(Scheduling::getRosterId, rosterId)
                .eq(Scheduling::getStatus, WorkerApplyStatusEnum.PASS)
                .eq(Scheduling::getLogicDel, Boolean.FALSE)
                .eq(Scheduling::getStoreId, storeId);
        return Result.ok(new Scheduling().selectList(lambdaQueryWrapper));
    }


    @ApiOperation("发型师删除指定日期排班")
    @PostMapping("/delschedul")
    public Result delschedul(@RequestBody SchedulDelVo schedulDelVo) {
        try {
            QueryWrapper<Scheduling> schedulingQueryWrapper = new QueryWrapper<>();
            schedulingQueryWrapper.eq("worker_id",schedulDelVo.getWorkerId());
            schedulingQueryWrapper.eq("date",schedulDelVo.getDelDate());
            schedulingQueryWrapper.eq("status",1);
            Scheduling scheduling = new Scheduling();
            scheduling.setStatus(WorkerApplyStatusEnum.DISMISSED);
            scheduling.setLogicDel(true);
            int update = schedulingMapper.update(scheduling, schedulingQueryWrapper);

            if (update>0){
                return Result.ok();
            }else {
                return Result.fail();
            }
        }catch (Exception e){
            return Result.fail();
        }
    }

    @ApiOperation("排班物资选择列表")
    @GetMapping("/authority")
    public Result getAuthorityGroup(@RequestParam(value = "workerId",required = false,defaultValue = "0") @ApiParam("员工id") Integer workerId,
                                    @RequestParam(value = "type", required = false,defaultValue = "0") @ApiParam("类型 0排班 1物资") Integer type) {
        List<AuthorityGroupVo> authorityGroup = workerAuthorityMapper.getAuthorityGroupfran(workerId, type);
        return Result.ok(authorityGroup);
    }


    @ApiOperation("查看当天考勤")
    @GetMapping("/checkToday")
    public Result checkToday(@DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull(message = "日期不能为空") Date date,
                             Integer storeId) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = dateFormat.format(date);
        List<CheckTodayUserVo> checkTodayUser = checkUserServiceImpl.selectCheckToday(dateStr,storeId);
        return Result.ok(checkTodayUser);
    }
}
